using System.Windows.Media.Imaging;
using AndyPike.Experiments.Fluent.Interfaces;

namespace AndyPike.Experiments.Fluent.Commands
{
    public class GreyscaleCommand : ICommand
    {
        public WriteableBitmap Execute(WriteableBitmap image)
        {
            GuardAgainst.ArgumentNull(image, "image");

            var info = new ImageInfo(image);
            var pixels = new byte[info.TotalBytes];
            image.CopyPixels(pixels, info.Stride, 0);

            for (var x = 0; x < info.TotalPixels; ++x)
            {
                var r = x * info.BytesPerPixel;
                var g = r + 1;
                var b = r + 2;
                var grey = (byte)(.299 * pixels[r] + .587 * pixels[g] + .114 * pixels[b]);

                pixels[r] = grey;
                pixels[g] = grey;
                pixels[b] = grey;
            }

            image.WritePixels(info.Rect, pixels, info.Stride, 0);

            return image;
        }
    }
}